package IOLearn;


import org.junit.jupiter.api.Test;

import java.io.*;

/**
 * @author Lenl
 * @version v1.0
 * @create 2021-06-05 23:37
 * @description
 *
 * 处理流之一：缓冲流
 * 1.缓冲流
 * BufferedInputStream
 * BufferedOutputStream
 * BufferedReader
 * BufferedWriter
 * 2.作用：提供流的读取、写入的速度，提高效率
 *
 * 3.处理流，就是“套接”在已有流的基础上
 *
 */
public class BufferedStreamTest {
    @Test
    public void BufferedStream(){
        String drc="D:\\大四相关文件\\音视频\\2021052917信管节目视频.mp4";
        String dest="D:\\Java Learn\\IOLearnTestFile\\videotest\\视频测试1.mp4";

        FileInputStream fis=null;
        FileOutputStream fos=null;
        BufferedInputStream bis=null;
        BufferedOutputStream bos=null;

        try {
            //1.造文件
            File srcFile=new File(drc);
            File destFile=new File(dest);
            //2.造流
            //2.1造了两个节点流
            fis=new FileInputStream(srcFile);
            fos=new FileOutputStream(destFile);
            //2.2造缓冲流
            bis=new BufferedInputStream(fis);
            bos=new BufferedOutputStream(fos);
            //3.复制的细节：读取、写入
            byte[] buffer=new byte[512];
            int len;
            long start=System.currentTimeMillis();
            while((len=bis.read(buffer))!=-1){
                bos.write(buffer,0,len);
            }
            long end=System.currentTimeMillis();
            System.out.println("耗时："+(end-start)+"毫秒"); //799毫秒
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //4.资源关闭
            //要求：先关闭外层流，再关闭内层流
            //说明：关闭外层流时，内层流会自动关闭！
            if(bis!=null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(bos!=null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Test
    public void BufferedRW() throws IOException {
        String src="D:\\Java Learn\\IOLearnTestFile\\test1\\dbcp.txt";
        String dest="D:\\Java Learn\\IOLearnTestFile\\testinit\\dbcp.txt";
        BufferedReader br=new BufferedReader(new FileReader(new File(src)));
        BufferedWriter bw=new BufferedWriter(new FileWriter(new File(dest)));
        //方式一：使用char[]
//        char[] buf=new char[20];
//        int len;
//        while((len=br.read(buf))!=-1){
//            bw.write(buf,0,len);
//            //bw.flush();
//        }
        //方式二：使用String
        String data;
        while((data=br.readLine())!=null){
            bw.write(data+"\n");//data中不包含换行符
            //bw.newLine();//换行
        }
        br.close();
        bw.close();
        System.out.println("复制完成！");
    }
}
